package com.jfl.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * 获取Ip地址
 * 
 * @author 赵炎
 * @version [V1.00, 2019年1月2日]
 * @since V1.00
 */
public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
    
    public static final String IP_URL = "http://ip.360.cn/IPQuery/ipquery";
    
    /** 
     * 获取IP地址以及运营商
     * @param ip
     * @return
     */
    public static String getRealAddressByIP(String ip)
    {
        String address = "未知";

        // 内网不查询
        if (IpUtil.internalIp(ip))
        {
            return "内网IP";
        }
        
        String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
        if (StringUtils.isEmpty(rspStr))
        {
            log.error("获取地理位置异常 {}", ip);
            return address;
        }
        JSONObject obj;
        try
        {
            obj = JSONObject.parseObject(rspStr);
            if (obj.getIntValue("errno") == 0) {
                //address = region + " " + city + " " + isp;
                address = obj.getString("data").replaceAll("\t", " ");
                
            }
//            JSONObject data = obj.getJSONObject("data");
//            String region = data.getString("region");
//            String city = data.getString("city");
//            String isp = data.getString("isp");
        }
        catch (Exception e)
        {
            log.error("获取地理位置异常 {}", ip);
        }
        return address;
    }
    public static void main(String[] args)
    {
        
        AddressUtils.getRealAddressByIP("222.94.195.9");
    }
}
